<?php

include("configuration.inc.php");
try {
//      error_log("Trying to Connect");
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
    die("Died in Connection");
}

$sql = "SELECT DAY(dateutc) AS Date, 
round(AVG(temp),2) as Temp,
round(MAX(temp),2) as MaxTemp,
round(MIN(temp),2) as MinTemp,
round(AVG(windspeedmph),2) AS WindSpeed,
round(AVG(barom),2) AS Pressure,
round(AVG(rain),2) AS Rain,
round(AVG(humidity),2) AS Humidity,
round(AVG(winddir),2) AS WindDirection, 
round(MAX(windgustmph),2) AS MaxWindGust,
round(AVG(dewpt),2) AS FeelsLike,
round(SUM(rain),2) AS TotalRain
FROM raw 
WHERE YEAR(dateutc) = YEAR(NOW()) AND MONTH(dateutc) = MONTH(NOW())
GROUP BY DAY(dateutc)
ORDER BY dateutc ASC LIMIT 31;";
try {
    $sth = $dbh->prepare($sql);
} catch (PDOException $e) {
    echo 'Prepare failed: ' . $e->getMessage();
    die("Died in Prepare");
}

try {
    $sth->execute();
} catch (PDOException $e) {
    echo 'Execution failed: ' . $e->getMessage();
    die("Died in execute");
}

$tableData = $sth->fetchAll(PDO::FETCH_ASSOC);
$jsonData = json_encode($tableData, JSON_NUMERIC_CHECK);

print $jsonData;
/*
[
  {
      "Date": "04/27/2013 15:14",
      "Time": " 15:14 BST ",
      "TempOut": 11.2,
      "FeelsLike": 8.8,
      "HumidityOut": 53,
      "WindDirection": " NE ",
      "WindAvg": 1,
      "WindGust": 2,
      "Rain": 0.0,
      "AbsPressure": 1010.0  },
 ]
*/ 
